package service

import (
	"errors"
	"github.com/zhengchalei/gadmin/framework"
	"github.com/zhengchalei/gadmin/project/system/model"
	"gorm.io/gorm"
)

func UserFindPage(query *model.SysUser, page *framework.ReqPage) ([]model.SysUser, int64) {
	var userAll []model.SysUser
	var count int64
	db := framework.DB.Order("ID DESC").Model(&model.SysUser{})
	if query.Username != "" {
		db.Where("username like ?", "%"+query.Username+"%")
	}
	if query.Nickname != "" {
		db.Where("nickname like ?", "%"+query.Nickname+"%")
	}
	if query.DeptId != 0 {
		db.Where("dept_id = ?", query.DeptId)
	}
	db.Count(&count)
	db.Joins("Dept").Preload("Roles").Offset(page.Offset).Limit(page.PageSize).Find(&userAll)
	return userAll, count
}

func UserFindAll() *[]model.SysUser {
	var userAll []model.SysUser
	framework.DB.Joins("Dept").Preload("Roles").Order("ID DESC").Find(&userAll)
	return &userAll
}

func UserFindById(id string) (*model.SysUser, error) {
	user := &model.SysUser{}
	if err := framework.DB.Joins("Dept").Preload("Roles").First(user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("记录不存在")
		}
		return nil, err
	}
	return user, nil
}

func UserSave(save *model.SysUser) error {
	return framework.DB.Save(save).Error
}

func UserUpdate(flush *model.SysUser) error {
	return framework.DB.Updates(flush).Error
}

func UserDelete(id string) error {
	var (
		data *model.SysUser
		err  error
	)
	if data, err = UserFindById(id); err != nil {
		return err
	}
	tx := framework.DB.Delete(data, id)
	if tx.RowsAffected == 0 {
		return tx.Error
	}
	return tx.Error
}
